package org.jeik.beackBeans.authentication;

import org.jeik.beackBeans.BeansBase;
import org.jeik.controllers.MsgsController;
import org.jeik.controllers.NavigationController;
import org.jeik.controllers.NavigationRule;
import org.jeik.data.dao.DataException;
import org.jeik.data.models.User;
import org.jeik.data.services.AuthenticationService;
import org.jeik.utils.Log;
import org.jeik.utils.StringUtils;
import org.jeik.utils.WebUtils;

public class ChangePasswordBean extends BeansBase {
	
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	
	private String oldPassword;
	private String newPassword;
	private String confirmPassword;
	
	
	public void changePassword(){
		
		User user = WebUtils.getAppSessionBean().getUser();
		
		if(!getOldPassword().equals(StringUtils.decryptString(user.getPassword(), user.hashCode()))){
			MsgsController.addErrorMessage("كلمة السر القديمة غير صحيحة");
			return;
		}
		
		
		if(!getNewPassword().equals(getConfirmPassword())){
			MsgsController.addErrorMessage("كلمة السر لا تتطابق مع التأكيد");
			return;
		}
		
		
		
		try {
			String newPasswordEncrypted = StringUtils.encryptString(getNewPassword(), user.hashCode());
			user.setPassword(newPasswordEncrypted);
			AuthenticationService.getInstance().changePassword(user);
		} catch (DataException e) {
			e.printStackTrace();
			Log.error(this, e.getMessage());
			MsgsController.addErrorMessage("فشلت عملية تغيير كلمة السر");
			return;
		}
        
        
        WebUtils.getAppSessionBean().setUser(user);
        
        MsgsController.addErrorMessage("تمت عملية تغيير كلمة السر بنجاح");
        NavigationController.navigate(NavigationRule.HOME);
    

	}
	
	public void navigateToChangePasswordPage(){
		NavigationController.navigate(NavigationRule.CHANGE_PASSWORD);
	}


	public String getOldPassword() {
		return oldPassword;
	}


	public void setOldPassword(String oldPassword) {
		this.oldPassword = oldPassword;
	}


	public String getNewPassword() {
		return newPassword;
	}


	public void setNewPassword(String newPassword) {
		this.newPassword = newPassword;
	}


	public String getConfirmPassword() {
		return confirmPassword;
	}


	public void setConfirmPassword(String confirmPassword) {
		this.confirmPassword = confirmPassword;
	}
	
	
}
